// @Date         2021-11-17
// @Author       Aaron Zhang
// @Description
// @FileName      trace.go

package middlewares

import (
	"context"
	"zin/framework/gin"
	"zin/framework/util"
	"net/http"
	"runtime/debug"
)

func Trace(c *gin.Context) {
	tracer := util.GetTraceProvider()
	//异常捕捉
	defer func() {
		if err := recover(); err != nil {
			util.GetLogProvider().Debug(context.Background(), "panic cached :", map[string]interface{}{"stack": string(debug.Stack())})
			c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
				"msg": "系统发生错误",
			})
		}
	}()
	traceCtx := tracer.ExtractHTTP(c.Request)
	tracer.WithTrace(c, traceCtx)

	//讲spanID等信息，插入刚才Req中， 以后的请求上可以得到
	injectReq := tracer.InjectHTTP(c.Request, traceCtx)
	c.Request = injectReq

	// 使用next执行具体的业务逻辑
	c.Next()

}
